<?php
/**
 * 工单解除绑定延期标签
 * User: Administrator
 * Date: 2018/8/5/005
 * Time: 22:06
 */

namespace app\lib\Order\OrderExtensionConfig;


use app\model\OrderBindingExtensionModel;

class OrderBindingEditExtension
{
    protected $orderId;
    protected $scenes;
    protected $content;
    public function __construct($orderId,$scenes = '',$content= '')
    {
        $this->orderId = $orderId;
        $this->scenes  = $scenes;
    }

    /**
     * 主动解除延期标签
     * 场景
     * 1、签收 2、交款 3、提前回复工单日志
     * @return bool
     * @throws \Exception
     */
    public function releaseBinding(){
        $model =  (new GetOrderBindingExtension($this->orderId));
        /*判断是否绑定延期标签*/
        if(!$model->isOrderBindingExtension()){
            return true;
        }
        $this->release();
    }

    /**
     * 自动解除延期表情
     * 用于定时任务
     * @return bool
     * @throws \Exception
     */
    public function  autoReleaseBinding(){
        $model =  (new GetOrderBindingExtension($this->orderId));
        /*判断是否绑定延期标签*/
        if(!$model->isOrderBindingExtension()){
            return true;
        }
        if($model->getEndTime()>time()){
            return true;
        }
        $this->scenes = 'reply';
        if(empty($this->content)){
            $this->content ='标签时效已结束，自动取消';
        }
        $this->release();
    }

    /**
     * 解除绑定动作
     * @throws \Exception
     */
    protected function release(){
        $model =  new OrderBindingExtensionModel();
        $map = [$model->_orderId=>$this->orderId,$model->_status=>1];
        if($this->scenes){
            switch ($this->scenes){
                case 'pay':
                    $map[$model->_configId] = ['eq',2];
                    break;
                case 'sign':
                    $map[$model->_configId] = ['eq',1];
                    break;
                case 'reply':
                    $map[$model->_configId] = ['not in' , [1,2]];
                    break;
            }
        }
        /*TODO 新增字段*/
        $result =  $model->where($map)->update($data = [$model->_status=>0,$model->_cancelReason=>$this->content]);
        if($result === false){
            exception('解除标签绑定失败');
        }
        return true;
    }
}